<template>
  <Back title="WebSocket通信" />
  
  <van-cell-group class="status-box">
    <van-cell title="连接状态" :value="connectionStatus" />
    <van-cell center title="服务器地址">
      <template #value>
        <van-field 
          v-model="serverUrl"
          placeholder="ws://localhost:8080"
          @blur="saveServerUrl"
        />
      </template>
    </van-cell>
  </van-cell-group>

  <van-button 
    block 
    type="primary"
    @click="toggleConnection"
    :loading="isConnecting"
    class="control-btn"
  >
    {{ isConnected ? '断开连接' : '建立连接' }}
  </van-button>

  <div class="message-area">
    <van-cell-group title="消息记录">
      <van-cell
        v-for="(message, index) in messages"
        :key="index"
        :title="message.time"
        :value="message.content"
        :class="message.type"
      />
    </van-cell-group>

    <van-field
      v-model="inputMessage"
      rows="2"
      autosize
      type="textarea"
      placeholder="输入要发送的消息"
      class="input-box"
    >
      <template #button>
        <van-button 
          size="small" 
          type="primary"
          @click="sendMessage"
          :disabled="!isConnected"
        >
          发送
        </van-button>
      </template>
    </van-field>
  </div>
</template>

<script setup>
import { ref, reactive, onUnmounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import { Toast } from 'vant';
import Back from '../utils/Back.vue';

const router = useRouter();
const serverUrl = ref(localStorage.getItem('websocketUrl') || 'ws://localhost:8080');
const inputMessage = ref('');
const isConnected = ref(false);
const isConnecting = ref(false);
const reconnectAttempts = ref(0);
const maxReconnectAttempts = 5;
const reconnectInterval = 5000;

const messages = reactive([]);
let socket = null;
let reconnectTimer = null;

const connectionStatus = computed(() => {
  if (isConnecting.value) return '连接中...';
  return isConnected.value ? '已连接' : '已断开';
});

const saveServerUrl = () => {
  localStorage.setItem('websocketUrl', serverUrl.value);
};

const addMessage = (content, type = 'send') => {
  messages.push({
    content,
    type,
    time: new Date().toLocaleTimeString()
  });
};

const connect = () => {
  if (!serverUrl.value) {
    Toast('请输入服务器地址');
    return;
  }

  isConnecting.value = true;
  socket = new WebSocket(serverUrl.value);

  socket.onopen = () => {
    isConnected.value = true;
    isConnecting.value = false;
    reconnectAttempts.value = 0;
    addMessage('连接成功', 'system');
  };

  socket.onmessage = (event) => {
    addMessage(event.data, 'receive');
  };

  socket.onerror = (error) => {
    console.error('WebSocket错误:', error);
    addMessage('连接异常', 'error');
    handleReconnection();
  };

  socket.onclose = () => {
    isConnected.value = false;
    addMessage('连接已关闭', 'system');
    handleReconnection();
  };
};

const handleReconnection = () => {
  if (reconnectAttempts.value < maxReconnectAttempts) {
    reconnectAttempts.value++;
    reconnectTimer = setTimeout(() => {
      connect();
    }, reconnectInterval);
  } else {
    Toast('已达到最大重连次数');
  }
};

const toggleConnection = () => {
  if (isConnected.value) {
    socket.close();
  } else {
    connect();
  }
};

const sendMessage = () => {
  if (!inputMessage.value.trim()) {
    Toast('请输入有效内容');
    return;
  }

  socket.send(inputMessage.value);
  addMessage(inputMessage.value, 'send');
  inputMessage.value = '';
};

onUnmounted(() => {
  if (socket) {
    socket.close();
  }
  clearTimeout(reconnectTimer);
});
</script>

<style scoped>
.status-box {
  margin: 12px;
}

.control-btn {
  margin: 15px;
  width: calc(100% - 30px);
}

.message-area {
  margin: 15px;
}

.input-box {
  margin-top: 15px;
}

.receive {
  background-color: #f7f8fa;
}

.send {
  background-color: #e8f4ff;
}

.error {
  color: #ee0a24;
}
</style>